﻿#include "netcomm.h"
#include "dlgstart.h"
#include <QDebug>

netComm::netComm(QObject *parent) : QObject(parent)
{
    m_parent = parent;
}

netComm::~netComm()
{
    ClearRobotCoreComm();
}

void netComm::InitRobotCoreComm()
{
    try{
        //连接本地服务器，初始化
        Ice::InitializationData iniData;
        iniData.properties = Ice::createProperties();
        //存放到bin\Out\Config\Ice\admin.ini文件中的键值对.
        //如果服务器在本地，使用Ice.Default.Locator;如果不在本地，使用Ice.Default.Router
        iniData.properties->setProperty("Ice.Default.Locator", "RobotIceGrid/Locator:tcp -h localhost -p 4061");
        ice = Ice::initialize(iniData);
        //获取代理
        m_audio   = Robot::AudioPrx::checkedCast(ice->stringToProxy("Audio"));
        m_motor   = Robot::MotorPrx::checkedCast(ice->stringToProxy("Motor"));
        m_script  = Robot::ScriptPrx::checkedCast(ice->stringToProxy("Script"));
        m_config  = Robot::ConfigPrx::checkedCast(ice->stringToProxy("Config"));
        m_json    = Robot::JsonPrx::checkedCast(ice->stringToProxy("Json"));
//        m_screen  = Robot::ScreenExPrx::checkedCast(ice->stringToProxy("ScreenEx"));
        m_pub     = Robot::PubPrx::checkedCast(ice->stringToProxy("Pub"));
        //
        Ice::ObjectPrx obj = ice->stringToProxy("PubCenter/TopicManager");
        m_topicManager = IceStorm::TopicManagerPrx::checkedCast(obj);
        //参数说明：第一个参数随便，第二个指定使用tcp协议
        Ice::ObjectAdapterPtr adapter = ice->createObjectAdapterWithEndpoints("MonitorAdapter", "tcp");
        Robot::PubPtr monitor = new PubCenter(NULL, (void*)this);
        //调用模式ice_oneway
        m_sub = adapter->addWithUUID(monitor)->ice_oneway();
        adapter->activate();

        if(m_motor)
        {
            m_motor->HeadEye(1,0);
            m_motor->BodyLed(2,true,true,true);
        }
    }
    catch (Ice::Exception& e)
    {
        m_szLog = QString("InitRobotCoreComm catch error=%1").arg(e.what());
        qDebug() << m_szLog.toUtf8().data();
    }
}

void netComm::ConnectRobotCoreComm()
{
    //订阅"Notify"数据
    if(m_sub){
        try{
            IceStorm::TopicPrx topic = m_topicManager->retrieve("Notify");
            IceStorm::QoS qos;
            topic->subscribeAndGetPublisher(qos, m_sub);
        }catch(Ice::Exception e){
            m_szLog = QString("ConnectRobotCoreComm catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
}

void netComm::ClearRobotCoreComm()
{
    //取消订阅"Notify"数据
    if(m_sub){
        try{
            IceStorm::TopicPrx topic = m_topicManager->retrieve("Notify");
            topic->unsubscribe(m_sub);
        }catch(Ice::Exception e){
            m_szLog = QString("ClearRobotCoreComm catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
    if(m_audio) m_audio->TtsStop();
    if(m_script) m_script->Stop();
    if(ice) ice->destroy();
}

void netComm::InitEngine()
{
    if(m_motor){
        try{
            //头部
            m_motor->HeadEnable(true,true);
            m_motor->HeadLrInit();
            m_motor->HeadUdInit();
            //左手电机
            m_motor->HandLEnable(true,true);
            m_motor->HandLSwingInit();
            m_motor->HandLExpandInit();
            //右手电机
            m_motor->HandREnable(true,true);
            m_motor->HandRSwingInit();
            m_motor->HandRExpandInit();

//            QThread::sleep(15);
            connect(&m_timer,&QTimer::timeout, [=] (){
                m_motor->HeadLrAngle(0,2);
                m_motor->HeadUdAngle(0,2);
                m_motor->HandLSwingAngle(0,2);
                m_motor->HandLExpandAngle(0,2);
                m_motor->HandRSwingAngle(0,2);
                m_motor->HandRExpandAngle(0,2);
                DlgStart* parent = (DlgStart*)m_parent;
                parent->m_bRobotStartSuc = true;
            });
            m_timer.setSingleShot(true);
            m_timer.start(15000);

        }catch(Ice::Exception& e){
            m_szLog = QString("InitEngine catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
}

void netComm::StopTTS()
{
    if(m_audio && m_script){
        try{
            m_audio->TtsStop();
            m_audio->MediaStop();
            m_script->Stop();
        }catch(Ice::Exception e){
            m_szLog = QString("StopTTS catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
}

void netComm::SendBehaviour(QString tts, QString speaker, int nSpeed, int nPicth, QString backmusic)
{
    if(m_audio && m_json){
        try{
            if(!m_timerautoAction.isActive()){
                connect(&m_timerautoAction,&QTimer::timeout, [=] (){
                    m_json->CallByClass("mauto");
                });
                m_timerautoAction.start(5000);
            }
            if(tts.length() > 1){
                m_audio->TtsSetVolume(99);
                m_audio->TtsPlayParams(tts.toStdString(), speaker.toStdString(), nSpeed, nPicth);
            }
            if(backmusic.length() > 1){
                m_audio->MediaSetVolume(85);
                m_audio->MediaPlay(backmusic.toStdString());
            }
        }catch(Ice::Exception e){
            m_szLog = QString("SendBehaviour catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
}

bool netComm::IsEndTTs()
{
    bool bEnd = true;
    if(m_audio){
        try{
            if(m_audio->TtsIsPlaying())
                bEnd = false;
            else
                bEnd = true;
        }catch(Ice::Exception e){
            m_szLog = QString("GetState catch error=%1").arg(e.what());
            qDebug() << m_szLog.toUtf8().data();
        }
    }
    return bEnd;
}

/**********************************************************************************
 *********************************************************************************
 *******************************接收平台的类***************************************
 *********************************************************************************
 *********************************************************************************
 *********************************************************************************
 *********************************************************************************/
PubCenter::PubCenter(QObject *parent, void *pFrm): QObject(parent)
{
}

void PubCenter::Notify(const std::string &msgtype, const std::string &msg, const Ice::Current &)
{

}

bool PubCenter::NotifyCloud(const std::string &, const Ice::Current &)
{
    return false;
}

void PubCenter::NotifyContral(bool, const Ice::Current &)
{

}

void PubCenter::NotifyTitleCloud(const std::string &, const std::string &, const Ice::Current &)
{

}

/////////////////////////////////////////

